package com.cq.controller;
     
    import com.baomidou.kaptcha.Kaptcha;
    import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
    import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
    import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
     
    @RestController
    public class KaptchaController {
        @Autowired
        private Kaptcha kaptcha;
     
        /**
         * 获取Kaptcha验证码
         */
        @GetMapping("/getKaptchaImg")
        public void getKaptchaImg() {
            //默认900秒
            kaptcha.render();
        }
     
        /**
         * 验证验证码
         *
         * @param code 验证码
         * @return
         */
        @GetMapping("/validCode")
        public String validCode(@RequestParam String code) {
            try {
                kaptcha.validate(code);
            } catch (Exception e) {
                if (e instanceof KaptchaIncorrectException) {
                    return "验证码不正确";
                } else if (e instanceof KaptchaNotFoundException) {
                    return "验证码未找到";
                } else if (e instanceof KaptchaTimeoutException) {
                    return "验证码过期";
                } else {
                    return "验证码渲染失败";
                }
            }
            return "验证通过";
        }
    }